<template>
  <div class="swiper-container" ref="swiperBox">
    <div class="swiper-wrapper">
      <slot />
    </div>
    <slot name="navigation-prev">
      <div ref="navigationPrev" class="swiper-button-prev"></div>
    </slot>
    <slot name="navigation-next">
      <div ref="navigationNext" class="swiper-button-next"></div>
    </slot>
    <slot name="pagination">
      <div v-if="config.pagination" ref="pagination" class="swiper-pagination"></div>
    </slot>
    <slot name="scrollbar">
      <div v-if="config.scrollbar" ref="scrollbar" class="swiper-scrollbar"></div>
    </slot>
  </div>
</template>

<script>
import 'swiper/css/swiper.css'
import Swiper from 'swiper'

export default {
  name: 'FlSwiper',
  data() {
    return {
      swiper: null,
    }
  },
  props: {
    config: {
      type: Object,
      default: () => ({}),
    },
  },
  methods: {
    newSwiper() {
      const { config } = this
      if (config.pagination === true) config.pagination = this.$refs.pagination
      if (typeof config.pagination === 'object' && !config.pagination.el)
        config.pagination.el = this.$refs.pagination

      if (config.navigation === true)
        config.navigation = { prevEl: this.$refs.navigationPrev, nextEl: this.$refs.navigationNext }
      if (typeof config.navigation === 'object') {
        if (!config.navigation.prevEl) config.navigation.prevEl = this.$refs.navigationPrev
        if (!config.navigation.nextEl) config.navigation.nextEl = this.$refs.navigationNext
      }

      if (config.scrollbar === true) config.scrollbar.el = this.$refs.scrollbar
      if (typeof config.scrollbar === 'object' && config.scrollbar.el)
        config.scrollbar.el = this.$refs.scrollbar
      this.swiper = new Swiper(this.$refs.swiperBox, config)
    },
    /**重载实例 */
    heavyLoad() {
      this.swiper.destroy()
      this.newSwiper()
    },
    /**上一页 */
    slidePrev() {
      this.swiper.slidePrev()
    },
    /**下一页 */
    slideNext() {
      this.swiper.slideNext()
    },
  },
  mounted() {
    this.newSwiper()
  },
}
</script>

<style lang="scss" scoped></style>
